package com.pipayshop.service.impl;



import cn.hutool.cache.CacheUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pipayshop.config.RedisConfig;
import com.pipayshop.domain.*;

import com.pipayshop.domain.dto.ShopCommodityDto;
import com.pipayshop.domain.dto.SkuDto;
import com.pipayshop.domain.vo.*;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.*;
import com.pipayshop.service.OnlineStoreShopCommodityService;
import com.pipayshop.service.OnlineStoreSkuService;
import com.pipayshop.utils.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.web.multipart.MultipartFile;


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiaoqiu
 * @date 2024/9/10 11:13
 * @description
 */
@Service
@Slf4j
public class OnlineStoreShopCommodityServiceImpl extends ServiceImpl<OnlineStoreShopCommodityMapper, ShopCommodity> implements OnlineStoreShopCommodityService {
    @Autowired
    private OnlineStoreShopCommodityMapper shopCommodityMapper;
    @Autowired
    private OnlineStoreShopMapper shopMapper;
    @Autowired
    private OnlineStoreShopCommodityEvaluateMapper shopCommodityEvaluateMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private OnlineStoreSkuService skuService;
    @Autowired
    private OnlineStoreShopFollowFocusMapper shopFollowFocusMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OnlineStoreSkuMapper skuMapper;

    @Override
    @CacheEvict(value = Constants.SHOPCOMMODITY_LIST_KEY ,allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(ShopCommodityDto shopCommodityDto) {
        validateShopCommodityDto(shopCommodityDto);

        ShopCommodity shopCommodity = new ShopCommodity();
        BeanUtils.copyProperties(shopCommodityDto, shopCommodity);
        handleCommonProperties(shopCommodity, shopCommodityDto);

        if (StringUtils.isEmpty(shopCommodityDto.getCommodityId())) {
            return addNewCommodity(shopCommodity, shopCommodityDto);
        } else {
            return updateExistingCommodity(shopCommodity, shopCommodityDto);
        }
    }

    private boolean addNewCommodity(ShopCommodity shopCommodity, ShopCommodityDto shopCommodityDto) {
        shopCommodity.setCommodityId(StringUtil.generateShortId());
        shopCommodity.setCreateTime(new Date());
        shopCommodity.setStatus(0);  // 初始状态
        shopCommodity.setSales(0);   // 初始销售量
        //设置价格 默认规格的价格中最低的
        shopCommodity.setPrice(shopCommodityDto.getSkuList().stream().map(Sku::getPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO));

        //设置库存
        shopCommodity.setInventory(shopCommodityDto.getSkuList().stream().mapToInt(Sku::getInventory).sum());
        int result = shopCommodityMapper.insert(shopCommodity);
        if (result < 1) {
            throw new BusinessException("insert_new_product_failed");
        }

        deductShopUploadBalance(shopCommodity.getShopId());
        saveSkus(shopCommodity.getCommodityId(), shopCommodityDto.getSkuList());

        return true;
    }

    private boolean updateExistingCommodity(ShopCommodity shopCommodity, ShopCommodityDto shopCommodityDto) {
        shopCommodity.setUpdateTime(new Date());
        if (shopCommodityDto.getDeleteImageList() != null && !shopCommodityDto.getDeleteImageList().isEmpty()) {
            if (shopMapper.updateDelFlag(shopCommodityDto.getDeleteImageList()) == 0) {
                throw new BusinessException("image_usage_update_failed");
            }
        }
        int result = shopCommodityMapper.update(shopCommodity, new QueryWrapper<ShopCommodity>()
                .eq("commodity_id", shopCommodity.getCommodityId()));
        if (result < 1) {
            throw new BusinessException("update_product_data_failed");
        }

        skuService.remove(new QueryWrapper<Sku>().eq("commodity_id", shopCommodity.getCommodityId()));
        saveSkus(shopCommodity.getCommodityId(), shopCommodityDto.getSkuList());

        return true;
    }

    private void deductShopUploadBalance(String shopId) {
        int update = shopMapper.update(null, new UpdateWrapper<Shop>()
                .eq("shop_id", shopId)
                .gt("shop_upload_balance", 0)
                .setSql("shop_upload_balance = shop_upload_balance - 1"));
        if (update < 1) {
            throw new BusinessException("store_product_shelf_remaining_decrease_failed");
        }
    }

    private void saveSkus(String commodityId, List<Sku> skuList) {
        if (skuList != null && !skuList.isEmpty()) {
            for (Sku sku : skuList) {
                sku.setCommodityId(commodityId);
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                sku.setDelFlag(0);
            }
            skuService.saveBatch(skuList);

        }
    }

    private void validateShopCommodityDto(ShopCommodityDto shopCommodityDto) {
        ValidationUtil.validateNotNull(shopCommodityDto, "request_data_required");
    }

    private void handleCommonProperties(ShopCommodity shopCommodity, ShopCommodityDto shopCommodityDto) {
        // 将支持发货地址集合转变为String
        shopCommodity.setAcceptAddressList(String.join(",", shopCommodityDto.getAcceptAddressList()));
        // 将商品详情图片集合转变为String
        shopCommodity.setDetailImages(String.join(",", shopCommodityDto.getDetailImages()));
        // 将商品图片集合转变为String
        shopCommodity.setImagsList(String.join(",", shopCommodityDto.getImageList()));
        // 将商品图片第一个图片作为商品头像
        shopCommodity.setAvatarImg(shopCommodityDto.getImageList().get(0));
        // 设置规格和分类ID
        shopCommodity.setSpecification(shopCommodityDto.getSpecification());
        shopCommodity.setCategoryId(shopCommodityDto.getCategoryId());
    }



//        // 4.商品数据添加到国家商品关联表-countryCommodity表
//        CountryCommodity countryCommodity = new CountryCommodity(null, applyItemCommodityDTO.getCountryCode(), commodityId, null, null);
//        int insert = countryCommodityMapper.insert(countryCommodity);



    @Override
    @Cacheable(value = Constants.SHOPCOMMODITY_LIST_KEY )
    public  ShopCommodityPageVo listCommodity(ShopCommodityDto shopCommodityDto) {
        // 分页参数
        int size = shopCommodityDto.getSize();
        int realStart = (shopCommodityDto.getStart() - 1) * size;
        shopCommodityDto.setStart(realStart);
//        查询符合条件的且库存大于0的商品集合
        List<ShopCommodityVo> pages = shopCommodityMapper.select(shopCommodityDto);
//      封装结果对象
        ShopCommodityPageVo shopCommodityPageVo = new ShopCommodityPageVo();
//      根据shopCommodityPageVo的commodityid设置sku集合
        pages.forEach(shopCommodityVo -> {
            List<Sku> skuList = skuService.list(new QueryWrapper<Sku>().eq("commodity_id", shopCommodityVo.getCommodityId()));
            shopCommodityVo.setSku(skuList);
        });
        shopCommodityPageVo.setList(pages);
        shopCommodityPageVo.setCount((long) pages.size());
        return shopCommodityPageVo;
    }

    @Override
    public String shopImagsUp(MultipartFile multipartFile) {
        return uploadImage(multipartFile, FileUploadUtil.SHOP_IMAGS_LIST);
    }

    @Override
    public String shopDetailImagsUp(MultipartFile multipartFile) {
        return uploadImage(multipartFile, FileUploadUtil.SHOP_DETAIL_IMAGS);
    }

    private String uploadImage(MultipartFile multipartFile, String storagePath) {
        List<String> imageSizeList = new ArrayList<>();
        imageSizeList.add(ImageConstants.ITEM_TOP_IMAGS_UP_SMALL);
        imageSizeList.add(ImageConstants.ITEM_TOP_IMAGS_UP_BIG);
        return FileUploadUtil.allUploadImageData(multipartFile, imageMapper, storagePath, imageSizeList);
    }


    /**
     * 查询商品库存
     *
     * @param commodityId 商品ID
     * @return 库存数量
     */
    @Override
    public Integer getInventoryByCommodityId(String commodityId) {
        QueryWrapper wrapper = new QueryWrapper<ShopCommodity>();
        wrapper.select("inventory");
        wrapper.eq("commodity_id",commodityId);
        ShopCommodity shopCommodityInfo = shopCommodityMapper.selectOne(wrapper);
        if (shopCommodityInfo == null) {
            log.warn("商品ID {} 对应的商品信息未找到", commodityId);
            return 0; // 或者返回默认值，如 0
        }
        return shopCommodityInfo.getInventory();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommodityDetailVO itemCommodityDetail(String commodityId) {
        // 获取网店的数据
//        ShopCommodity itemCommodityInfo = shopCommodityMapper.selectOne(new QueryWrapper<ShopCommodity>()
//                .eq("commodity_id", commodityId));
        ShopCommodity itemCommodityInfo = shopCommodityMapper.itemCommodityDetail(commodityId);
        if(itemCommodityInfo.getInventory()<0){
            throw new BusinessException("product_inventory_insufficient");
        }
        String shopId = itemCommodityInfo.getShopId();
        Map<String, List<String>> typeMap = new HashMap<>();
        // 转移部分非json型的数据
        CommodityDetailVO commodityDetailVO = new CommodityDetailVO();
        // 属性转移
        BeanUtils.copyProperties(itemCommodityInfo, commodityDetailVO);
        //使用stream流将字符串类型的acceptAddressList转化为List<String>
        commodityDetailVO.setAcceptAddressList(Arrays.stream(itemCommodityInfo.getAcceptAddressList().toString().split(",")).toList());

        Integer piShoper =shopCommodityMapper.selectPiShoper(shopId);
        commodityDetailVO.setPiShoper(piShoper);

        String acceptAddressListString = itemCommodityInfo.getAcceptAddressList();
        if (acceptAddressListString != null) {
            ArrayList<String> strings = new ArrayList<>();
            if (acceptAddressListString.contains("\\.")) {
                String[] split = acceptAddressListString.split("\\.");
                for (String s : split) {
                    strings.add(s);
                }
            }else {
             strings.add(acceptAddressListString);
            }
//            commodityDetailVO.setAcceptAddressList(JSON.parseArray(acceptAddressListString, String.class));
            commodityDetailVO.setAcceptAddressList(strings);

        }
        String imagsListString = itemCommodityInfo.getImagsList();
        if (imagsListString != null) {
            //将字符串形式（不是json格式）的图片id集合转化为图片路径集合（不使用parseArray方法）
            List<String> imageIdList = Arrays.stream(imagsListString.toString().split(",")).toList();
            commodityDetailVO.setImagsList(imageIdList);
        }
        String imagsListCodeString = itemCommodityInfo.getImagsListCode();
        if (imagsListCodeString != null) {
            //将字符串形式（不是json格式）的图片id集合转化为图片路径集合（不使用parseArray方法）
            List<String> imageCodeIdList = Arrays.stream(imagsListCodeString.toString().split(",")).distinct().toList();
            commodityDetailVO.setImagsListCode(imageCodeIdList);
        }
        String couponsListString = itemCommodityInfo.getCouponsList();
        if (couponsListString != null) {
            commodityDetailVO.setCouponsList(Arrays.stream(couponsListString.split(",")).toList());
        }

        String detailImagList = itemCommodityInfo.getDetailImages();
        if (detailImagList != null) {
            List<String> imageList = Arrays.stream(detailImagList.split(",")).toList();
            commodityDetailVO.setDetailImages(imageList);
        }
        String detailImagListCode = itemCommodityInfo.getDetailImagesCode();
        if (detailImagListCode != null) {
            List<String> imageCodeList = Arrays.stream(detailImagListCode.split(",")).distinct().toList();
            commodityDetailVO.setDetailImagesCode(imageCodeList);
        }


//        String brandId = itemCommodityInfo.getBrandId();
//        // 解析品牌字段
//        if (brandId != null) {
//            BrandInfo brandInfo = brandInfoMapper.selectOne(new QueryWrapper<BrandInfo>()
//                    .eq("b_id", brandId)
//                    .eq("del_flag", 0)
//                    .select("title"));
//            if (brandInfo != null) {
//                comodityDetailVO.setTitle(brandInfo.getTitle());
//            }
//        }
        // 封装该商品的评论总数
        int evaluateCount = shopCommodityEvaluateMapper.selectCount(new QueryWrapper<ShopCommodityEvaluate>()
                .eq("commodity_id", commodityId)
                .eq("status", 0))
                .intValue();
        commodityDetailVO.setEvaluateCount(evaluateCount);
        // 封装该商品的所在店铺数据
        ShopVO itemVO = shopMapper.selectBasicData(shopId);
        int fanSum = Math.toIntExact(shopFollowFocusMapper
                .selectCount(new QueryWrapper<ShopFollowFocus>()
                .eq("shop_id", shopId)
                .eq("status", 0)));

        int commoditySum = Math.toIntExact(shopCommodityMapper.selectCount(new QueryWrapper<ShopCommodity>()
                .eq("shop_id", shopId)
                .eq("status", 0)));
        itemVO.setFanSum(fanSum);
        itemVO.setShopId(shopId);
        itemVO.setShopCommoditySum(commoditySum);
        commodityDetailVO.setShopVO(itemVO);

        //封装SkuList<Sku>
        List<Sku> skus = skuMapper.selectAll( commodityId);

        commodityDetailVO.setSku(skus);


        return commodityDetailVO;
    }

    @Override
    public Integer upOrdown(String commodityId, Integer status) {
        //清除商品缓存
        deleteKeysByPrefix(Constants.SHOPCOMMODITY_LIST_KEY);
        return shopCommodityMapper.update(null, new UpdateWrapper<ShopCommodity>()
                .eq("commodity_id", commodityId)
                .set("status", status)
        );

    }
    public void deleteKeysByPrefix(String prefix) {
        // 使用 keys 命令获取所有匹配的键
        Set<String> keys = redisTemplate.keys(prefix + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }}

    @Override
    public Integer delCommodity(String commodityId) {
        shopCommodityMapper.delete( new UpdateWrapper<ShopCommodity>()
                .eq("commodity_id", commodityId)
        );
        int delete = skuMapper.delete(new UpdateWrapper<Sku>().eq("commodity_id", commodityId));
        //删除商品列表缓存
        deleteKeysByPrefix(Constants.SHOPCOMMODITY_LIST_KEY);
        return delete;
    }

//    /**
//     * 根据用户id查询 对应的 网店收藏列表
//     */
//    @Override
//    public PageVo getCollectList(Integer page, Integer limit, String userId) {
//        Long integer = shopCommodityMapper.selectAllCollectProductByUserId(userId);
//        List<ShopCommodityCollectionVo> itemCommodityInfoVOS = shopCommodityMapper.selectCollectProductByUserId((page - 1) * limit, limit, userId);
//        return new PageVo(integer, itemCommodityInfoVOS);
//    }
}
